package com.job.framework.config.sharding;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;

/**
 * 表精确分片算法
 *
 * @author sunq
 */
public class PreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    /**
     * 精确分片算法
     *
     * @param availableTargetNames 所有配置的表列表，这里代表所匹配到库的所有表
     * @param shardingValue        分片值，也就是dau_id的值
     * @return                     所匹配表的结果
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {

        final Date value = shardingValue.getValue();

        if (ObjectUtil.isNull(value)) throw new UnsupportedOperationException("preciseShardingValue is null");

        final String yearMonth = DateUtil.format(value, DatePattern.SIMPLE_MONTH_PATTERN);
        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(yearMonth)) {
                return availableTargetName;
            }
        }
        throw new UnsupportedOperationException();
    }

}
